package com.wanjia.estate.crontab;

import com.wanjia.estate.properties.FolderPathProperties;
import com.wanjia.estate.utils.FolderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

@Component
@Slf4j
public class TimeTaskDelZips {

    @Autowired
    private FolderPathProperties folderPathProperties;

    @Scheduled(cron = "0 15 10 L * ?")
    public void run() {
        File folder = new File(folderPathProperties.getZippath());
        if (!folder.exists()) {
            folder.mkdir();
        }

        //获取30天之前的日期
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -30);
        Date date = calendar.getTime();

        // 将Date转换为Instant
        Instant instant = date.toInstant();

        // 创建ZonedDateTime对象
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = instant.atZone(zoneId);

        // 从ZonedDateTime中获取LocalDate
        LocalDate cutoffDate = zdt.toLocalDate();

        deleteOldFolders(folder.getAbsolutePath(),cutoffDate);
        log.info("文件信息压缩包删除");
    }


    //删除指定日期前的文件夹
    private static void deleteOldFolders(String directoryPath, LocalDate cutoffDate) {
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            return;
        }

        for (File file : directory.listFiles()) {
            if (file.isDirectory()) {
                if (LocalDate.ofEpochDay(file.lastModified() / 86400000L).isBefore(cutoffDate)) {
                    deleteOldFolders(file.getAbsolutePath(), cutoffDate);
                    file.delete();
                }
            }
        }
    }
}
